package com.orkasgb.framework.springsecurity.sms;

import com.orkasgb.framework.springsecurity.OrkasgbJWTSecurityContextRepository;
import com.orkasgb.framework.springsecurity.usernamepassword.OrkasgbFailureHandler;
import com.orkasgb.framework.springsecurity.usernamepassword.OrkasgbSuccessHandle;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractAuthenticationFilterConfigurer;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 自定义配置，主要是配置新的认证方法
 *
 * @date
 * @since
 */
public class OrkasgbSMSSecurityConfig<H extends HttpSecurityBuilder<H>> extends
        AbstractAuthenticationFilterConfigurer<H, OrkasgbSMSSecurityConfig<H>, OrkasgbSMSAuthencationFilter> {

    private final OrkasgbSMSAuthenticationProvider orkasgbSMSAuthenicationProvider;

    private final OrkasgbSuccessHandle orkasgbSuccessHandle;

    private final OrkasgbFailureHandler orkasgbFailureHandler;

    private final OrkasgbJWTSecurityContextRepository orkasgbJWTSecurityContextRepository;

    public OrkasgbSMSSecurityConfig() {
        super(new OrkasgbSMSAuthencationFilter(), "/codeLogin");
        this.orkasgbSMSAuthenicationProvider = new OrkasgbSMSAuthenticationProvider();
        this.orkasgbFailureHandler = new OrkasgbFailureHandler();
        this.orkasgbSuccessHandle = new OrkasgbSuccessHandle();
        this.orkasgbJWTSecurityContextRepository = new OrkasgbJWTSecurityContextRepository();
    }

    @Override
    protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) {
        return new AntPathRequestMatcher("/codeLogin", "POST");
    }

    @Override
    public void configure(H http) throws Exception {
        OrkasgbSMSAuthencationFilter orkasgbSMSAuthenticationFilter = new OrkasgbSMSAuthencationFilter();
        // 设置 AuthenticationManager
        orkasgbSMSAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 分别设置成功和失败处理器
        orkasgbSMSAuthenticationFilter.setAuthenticationSuccessHandler(orkasgbSuccessHandle);
        orkasgbSMSAuthenticationFilter.setAuthenticationFailureHandler(orkasgbFailureHandler);
        orkasgbSMSAuthenticationFilter.setSecurityContextRepository(orkasgbJWTSecurityContextRepository);

        // 创建 SmsCodeAuthenticationProvider 并设置 userDetailsService
        // 将Provider添加到其中
        http
        .authenticationProvider(this.orkasgbSMSAuthenicationProvider)
        // 将过滤器添加到UsernamePasswordAuthenticationFilter后面
        .addFilterBefore(orkasgbSMSAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        super.configure(http);
    }
}
